package com.lcy.demo;

import okio.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by loucunyin on 2/16/17.
 */
public class InitProjectUtil {
    private static final String FORMAT= "compileSdkVersion=25\n" +
            "buildToolsVersion=\"25.0.2\"\n" +
            "supportLibsVersion=25.0.0\n" +
            "gradleVersion=2.2.2\n" +
            "root=/home/loucunyin/workspace/Android/T-MVP/";
    private static final String GRADLE = "'com.android.tools.build:gradle:(.*)'";
    private static final String SUPPORT = "'com.android.support:[\\S^:]+:(.*)'";
    private static final String SDK = "compileSdkVersion\\s+([0-9]*)";
    private static final String BUILD = "buildToolsVersion\\s+(.*)";

    private static final String NAME = "build.gradle";


    private String mGradleVersion;
    private String mSupportLibsVersion;
    private String mSDKVersion;
    private String mBuildToolVersion;
    private String mProjectRootPath;

    private File mRoot;

    public static void main(String[] args) {
        boolean isSuccess = false;

        Scanner scanner = new Scanner(System.in);
        while (!isSuccess) {
            System.out.printf("#配置文件格式:%n%n%s%n%n",FORMAT);
            System.out.printf("#请输入配置文件的路径:");
            String path = scanner.next();
            if(path.equals("q")){
                break;
            }
            InitProjectUtil util = null;

            try {
                util = new InitProjectUtil(path);
                util.initProjectGradleFile();
                util.initModuleGradleFile();
                isSuccess = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private InitProjectUtil(String path) {
        File file = new File(path);
        if (!file.exists() || !file.isFile()) {

            throw new RuntimeException(String.format("配置文件: %s 不存在",file.getAbsoluteFile()));
        }
        Properties bundle = new Properties();
        try {
            bundle.load(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        mGradleVersion = bundle.getProperty("gradleVersion");
        mSupportLibsVersion = bundle.getProperty("supportLibsVersion");
        mSDKVersion = bundle.getProperty("compileSdkVersion");
        mBuildToolVersion = bundle.getProperty("buildToolsVersion");
        mProjectRootPath = bundle.getProperty("root");
    }


    private void initProjectGradleFile() throws IOException {
        File gradleFile = getGradleFile(mProjectRootPath);
        if (gradleFile == null) {
            return;
        }

        printGradleFilePath(gradleFile);

        String string = getStringFromFile(gradleFile);
        string = replace(string, GRADLE, mGradleVersion, 1);
        writeStringToFile(string, gradleFile);

    }

    public void initModuleGradleFile() throws IOException {
        if (!isValidRoot()) {
            return;
        }

        File[] files = mRoot.listFiles();
        for (File file : files) {
            if (file != null && file.exists() && file.isDirectory()) {
                initModuleGradleFile(file);
            }
        }
    }

    private void initModuleGradleFile(File file) throws IOException {
        if (file == null || !file.exists() || !file.isDirectory()) {
            return;
        }
        File gradleFile = getGradleFile(file);
        if (gradleFile == null) {
            return;
        }

        printGradleFilePath(gradleFile);

        String string = getStringFromFile(gradleFile);
        string = replace(string, SDK, mSDKVersion, 1);
        string = replace(string, BUILD, mBuildToolVersion, 1);
        string = replace(string, SUPPORT, mSupportLibsVersion, 1);
        writeStringToFile(string, gradleFile);
    }

    private void printGradleFilePath(File gradleFile){
        System.out.printf("%n%ngradle 文件路径:%s%n%n",gradleFile.getAbsolutePath());
    }


    private boolean isValidRoot() {
        // 根目录不是一个目录
        if (mRoot == null) {
            mRoot = new File(mProjectRootPath);
        }

        if (!mRoot.exists() || !mRoot.isDirectory()) {
            return false;
        }
        return true;
    }

    private File getGradleFile(String path) {
        // 根目录不是一个目录
        File file = new File(path);
        return getGradleFile(file);
    }

    private File getGradleFile(File file) {
        if (!file.exists() || !file.isDirectory()) {
            return null;
        }

        // gradle 文件不存在
        String filePath = file.getAbsolutePath() + File.separator + NAME;
        File gradleFile = gradleFile = new File(filePath);
        if (!gradleFile.exists() && !gradleFile.isFile()) {
            return null;
        }
        return gradleFile;
    }

    private String getStringFromFile(File file) throws IOException {
        if (file == null) {
            return null;
        }

        Source source = Okio.source(file);
        BufferedSource bufferedSource = Okio.buffer(source);
        String string = bufferedSource.readString(Charset.defaultCharset());
        bufferedSource.close();
        return string;
    }

    public void writeStringToFile(String string, File file) throws IOException {
        Sink sink = Okio.sink(file);
        BufferedSink bufferedSink = Okio.buffer(sink);
        bufferedSink.writeString(string, Charset.defaultCharset());
        bufferedSink.flush();
        bufferedSink.close();
    }


    private String replace(String string, String targetRgx, String replace, int replacePosition) {
        Pattern pattern = Pattern.compile(targetRgx);
        Matcher matcher = pattern.matcher(string);
        while (matcher.find()) {
            String gradleLine = matcher.group();
            if (replacePosition <= matcher.groupCount()) {
                String replaceLine = gradleLine.replace(matcher.group(replacePosition), replace);
                string = string.replace(gradleLine, replaceLine);
                System.out.printf("    replace : %-50s    to : %-50s %n", gradleLine, replaceLine);
            }
        }
        return string;
    }

    @Override
    public String toString() {
        return "InitProjectUtil{" +
                "mGradleVersion='" + mGradleVersion + '\'' +
                ", mSupportLibsVersion='" + mSupportLibsVersion + '\'' +
                ", mSDKVersion='" + mSDKVersion + '\'' +
                ", mBuildToolVersion='" + mBuildToolVersion + '\'' +
                ", mProjectRootPath='" + mProjectRootPath + '\'' +
                '}';
    }

}
